/**
 * yeahmobi.com Inc.
 * Copyright © 2014 YeahMobi | All Rights Reserved.
 */

package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.FbUserPermissionRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.AdAccountPermission;
import com.ndp.fb.rdb.model.AdaccountPermissionExt;
import com.ndp.fb.redis.api.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Title: FbUserPermissionRdbServiceImpl.java
 * @Copyright: Copyright © 2015
 * @Description:
 * @Company: yeahmobi
 * @Created on 下午4:38:35
 * @author giser.yang
 */
@Service
public class FbUserPermissionRdbServiceImpl extends DaoTemplate implements FbUserPermissionRdbService {

    @Autowired
    private RedisClient redisClient;

	/**
	 * @discription
	 * @author giser.yang 创建时间 2015年6月2日 下午4:38:35
	 * @param adaccountId
	 * @param fbUserId
	 * @return
	 * @see com.ndp.fb.rdb.api.FbUserPermissionRdbService#getUserpermissions(java.lang.Long,
	 *      java.lang.Long)
	 */

	@Override
	public List<AdAccountPermission> getUserpermissions(Long adaccountId,
			Long fbUserId) {
		String sql = "SELECT * FROM fb_userpermissions_adaccounts WHERE fb_account_id=? and fb_user_id=? and status = 'ACTIVE'";
		return getJdbcTemplate().query(sql, new Object[] { adaccountId, fbUserId }, DefaultRowMapper.autoRowMapper(AdAccountPermission.class));
	}

	/**
	 * @discription
	 * @author giser.yang 创建时间 2015年6月2日 下午4:38:35
	 * @param adaccountId
	 * @param fbUserId
	 * @param fbBusinessId
	 * @return
	 * @see com.ndp.fb.rdb.api.FbUserPermissionRdbService#getUserpermission(java.lang.Long,
	 *      java.lang.Long, java.lang.Long)
	 */

	@Override
	public AdAccountPermission getUserpermission(Long adaccountId, Long fbUserId,
			Long fbBusinessId) {
		String sql = "SELECT * FROM fb_userpermissions_adaccounts WHERE fb_account_id=? and fb_user_id=? and fb_business_id=? and status = 'ACTIVE'";
		return findOne(sql, new Object[]{adaccountId,
				fbUserId, fbBusinessId}, DefaultRowMapper.autoRowMapper(AdAccountPermission.class));
	}

	@Override
	public AdAccountPermission getUserpermissionAllStatus(Long adaccountId, Long fbUserId,
												 Long fbBusinessId) {
		String sql = "SELECT * FROM fb_userpermissions_adaccounts WHERE fb_account_id=? and fb_user_id=? and fb_business_id=?";
		return findOne(sql, new Object[] { adaccountId,
				fbUserId, fbBusinessId }, DefaultRowMapper.autoRowMapper(AdAccountPermission.class));
	}

	/**
	 * @discription 已经增加了redis乐观锁不会重复入库
	 * @author giser.yang 创建时间 2015年6月2日 下午4:38:35
	 * @param userPermission
	 * @return
	 * @see com.ndp.fb.rdb.api.FbUserPermissionRdbService#saveorupdateUserPermission(com.ndp.fb.rdb.model.AdAccountPermission)
	 */

	@Override
	public Long saveorupdateUserPermission(final AdAccountPermission userPermission) {
		String key = "ADACCOUNTPERMISSION"+userPermission.getFbBusinessId()+userPermission.getFbUserId()+userPermission.getFbAccountId();
		if(!redisClient.setNx(key, userPermission)){
			//这里加个乐观锁保证不会重复录入
			return 0L;
		}
		try {
			redisClient.expire(key, 5, TimeUnit.SECONDS.name());
			AdAccountPermission userPermission1 = this.getUserpermissionAllStatus(
					userPermission.getFbAccountId(), userPermission.getFbUserId(),
					userPermission.getFbBusinessId());
			if (userPermission1 != null) {
				this.updatePermission(userPermission);
				return userPermission1.getId();
			} else {
				return this.saveUserPermission(userPermission);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			redisClient.delete(key);
		}
		return 0L;
	}

	@Override
	public Long saveUserPermission(final AdAccountPermission userPermission) {
		return saveResultId(userPermission);
//		KeyHolder keyHolder = new GeneratedKeyHolder();
//		getJdbcTemplate().update(new PreparedStatementCreator() {
//			@Override
//			public PreparedStatement createPreparedStatement(Connection con)
//					throws SQLException {
//				String sql = "INSERT INTO fb_userpermissions_adaccounts (fb_account_id,fb_user_id,fb_business_id,role,status) "
//						+ " VALUES(?,?,?,?,?)";
//				PreparedStatement ps = con.prepareStatement(sql,
//						Statement.RETURN_GENERATED_KEYS);
//				ps.setObject(1, userPermission.getFbAccountId());
//				ps.setObject(2, userPermission.getFbUserId());
//				ps.setObject(3, userPermission.getFbBusinessId());
//				ps.setObject(4, userPermission.getRole());
//				ps.setObject(5, userPermission.getStatus());
//				return ps;
//			}
//		}, keyHolder);
//		return keyHolder.getKey().longValue();
	}

	private Integer updatePermission(final AdAccountPermission userPermission) {
		return getJdbcTemplate().update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				String sql = "UPDATE fb_userpermissions_adaccounts SET "
						+ "role = ?,status = ? where fb_account_id = ? and fb_user_id = ? and fb_business_id = ?";
				PreparedStatement ps = con.prepareStatement(sql);
				ps.setObject(1, userPermission.getRole());
				ps.setObject(2, userPermission.getStatus());
				ps.setObject(3, userPermission.getFbAccountId());
				ps.setObject(4, userPermission.getFbUserId());
				ps.setObject(5, userPermission.getFbBusinessId());
				return ps;
			}
		});
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月3日 下午1:34:57      
	 * @param adaccountId
	 * @return     
	 * @see com.ndp.fb.rdb.api.FbUserPermissionRdbService#getUserpermissions(java.lang.Long)     
	 */  
	@Override
	public List<AdAccountPermission> getUserpermissions(Long adaccountId) {
	    //add status = active 判断状态  by giser
		String sql = "SELECT t1.* FROM fb_userpermissions_adaccounts t1, fb_user t2 WHERE t1.fb_user_id = t2.fb_user_id AND t2.is_invalid = 0 AND t1.fb_account_id = ? and t1.status = 'ACTIVE'";
		return getJdbcTemplate().query(sql, new Object[]{adaccountId},
				DefaultRowMapper.autoRowMapper(AdAccountPermission.class));
	}

	@Override
	public List<AdAccountPermission> getUserpermissionsByUserId(String userId) {
		String sql = "SELECT t1.* FROM fb_userpermissions_adaccounts t1, fb_user t2 WHERE t1.fb_user_id = t2.fb_user_id AND t2.is_invalid = 0 AND t2.user_id = ? and t1.status = 'ACTIVE'";
		return getJdbcTemplate().query(sql, new Object[]{userId}, DefaultRowMapper.autoRowMapper(AdAccountPermission.class));
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月3日 下午2:55:34      
	 * @param fbUserId
	 * @return     
	 * @see com.ndp.fb.rdb.api.FbUserPermissionRdbService#getUserpermissionsByFbUserId(java.lang.Long)     
	 */  
	    
	@Override
	public List<AdAccountPermission> getUserpermissionsByFbUserId(Long fbUserId) {
		String sql = "SELECT * FROM fb_userpermissions_adaccounts WHERE fb_user_id=? and status = 'ACTIVE'";
		return getJdbcTemplate().query(sql, new Object[] { fbUserId},
				DefaultRowMapper.autoRowMapper(AdAccountPermission.class));
	}

	/** 
	 * @discription
	 * @author giser.yang       
	 * 创建时间 2015年6月5日 下午7:11:39      
	 * @param userPermission
	 * @return     
	 * @see com.ndp.fb.rdb.api.FbUserPermissionRdbService#deleteUserPermission(com.ndp.fb.rdb.model.AdAccountPermission)     
	 */  
	    
	@Override
	public Integer deleteUserPermission(final AdAccountPermission userPermission) {
		String sql = "delete from fb_userpermissions_adaccounts where fb_account_id = ? and fb_user_id = ? and fb_business_id = ?";
		getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setObject(1, userPermission.getFbAccountId());
				ps.setObject(2, userPermission.getFbUserId());
				ps.setObject(3, userPermission.getFbBusinessId());
            }

            @Override
            public int getBatchSize() {
                return 1;
            }
        });
        return 1;
	}

	@Override
	public List<AdaccountPermissionExt> getUserpermissionExts(Long adaccountId) {
		String sql = "SELECT u.user_id,u.access_token,a.* FROM fb_user u inner join fb_userpermissions_adaccounts a on u.fb_user_id = a.fb_user_id  where a.fb_account_id = ? and a.status = 'ACTIVE'";
		return getJdbcTemplate().query(sql, new Object[] {adaccountId}, DefaultRowMapper.autoRowMapper(AdaccountPermissionExt.class));
	}

	@Override
	public Integer deleteUserPermissionByFbUserId(final Long fbUserId) {
		String sql = "update fb_userpermissions_adaccounts set status = ? where fb_user_id = ?";
		getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setObject(1,"DISABLE");
				ps.setObject(2, fbUserId);
			}
			@Override
			public int getBatchSize() {
				return 1;
			}
		});
		return 1;
	}

	@Override
	public List<AdaccountPermissionExt> getUserpermissionExts(Long adaccountId, String userId) {
		String sql = "select  fu.user_id,fu.access_token,fua.* from user u,fb_user fu,fb_userpermissions_adaccounts fua where u.ticket = fu.user_id and fua.fb_user_id  = fu.fb_user_id and fua.status = 'ACTIVE' and fua.fb_account_id = ? and u.ticket = ?";
		return getJdbcTemplate().query(sql, new Object[] {adaccountId,userId}, DefaultRowMapper.autoRowMapper(AdaccountPermissionExt.class));
	}
}
